// TS 类型保护的使用说明
interface Attachment {
  raw: string
}

interface AttachmentForImage extends Attachment {
  url: string
  width: number
  height: number
}

interface AttachmentForVideo extends Attachment {
  url: string
  duration: number
  width: number
  height: number
}

interface AttachmentForFile extends Attachment {
  url: string
}

interface Message {
  /**
   * 消息的类型即可能是图片，视频，文件, 也可能是最基础的自定义消息
   */
  attach: Attachment | AttachmentForImage | AttachmentForVideo | AttachmentForFile
}

export function getMessageAttachmentType(message: Message): string {
  // 使用类型保护判定
  if ('url' in message.attach) {
    if ('duration' in message.attach) {
      // message.attach 到这里就会自动推导出拥有 url, duration, width, height, 是一个 AttachmentForVideo 类型
      return 'video'
    } else if ('width' in message.attach) {
      // 推导出 message.attach 是 AttachmentForImage 类型
      return 'image'
    } else {
      // 推导出 message.attach 是 AttachmentForFile 类型
      return 'file'
    }
  } else {
    return 'custom'
  }
}

// 测试代码
// let imageMessage: Message = {
//   attach: { raw: 'some data', url: 'https://example.com/image.jpg', width: 800, height: 600 }
// }

// let videoMessage: Message = {
//   attach: { raw: 'some video data', url: 'https://example.com/video.mp4', duration: 120, width: 1280, height: 720 }
// }

// let fileMessage: Message = {
//   attach: { raw: 'some file data', url: 'https://example.com/document.pdf' }
// }

// console.log(getMessageAttachmentType(imageMessage)) // Output: image
// console.log(getMessageAttachmentType(videoMessage)) // Output: video
// console.log(getMessageAttachmentType(fileMessage)) // Output: file
